<template>
  <div class="markdown">
    <v-md-editor
      v-model="content"
      :left-toolbar="toolbar"
      :mode="mode"
      :height="height"
      :tab-size="tabsize"
      :toc-nav-position-right="tocNavPositionRight"
      :default-show-toc="defaultShowToc"
      :placeholder="placeholder"
      :disabled-menus="[]"
      :width="width"
      :before-preview-change="beforeChange"
    ></v-md-editor>
  </div>
</template>

<script>
export default {
  //文档地址https://ckang1229.gitee.io/vue-markdown-editor/zh/api.html#props
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      String,
      default: "540px",
    },
    toolbar: {
      //undo撤回 redo重做 clear清除 h标题 bold粗体 italic斜体 strikethrough删除线 quote引用 ul有序列表
      //ol无序 table表格 hr分割线 link链接 tip提示 code代码
      type: String,
      default:
        "undo redo clear | h bold italic strikethrough quote | ul ol table hr | link tip code | emoji",
    },
    mode: {
      type: String,
      default: "editable",
    },
    tabsize: {
      type: Number,
      default: 2,
    },
    tocNavPositionRight: {
      type: Boolean,
      default: false,
    },
    defaultShowToc: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "",
    },
    detailContent: {
      type: String,
      default: ``,
    },
  },
  data() {
    return {
      content: ``,
    };
  },
  watch: {},
  methods: {
    clearContent() {
      this.content = ``;
    },
    beforeChange(text, next) {
      const BASE_URL = import.meta.env.VITE_APP_URL;
      text = text.replace(
        /!\[(.*?)\]\((grape-file\/.*?\.(jpg|png|gif))\)(\{\{\{.*?\}\}\})?/g,
        (match, alt, path, ext, attrs) => {
          // 拼接新路径
          const newPath = `${BASE_URL}/${path.replace(
            "grape-file",
            "grape-file"
          )}`;
          console.log(`![${alt}](${newPath})${attrs || ""}`, 222);

          // 保留属性和格式
          return `![${alt}](${newPath})${attrs || ""}`;
        }
      );
      next(text);
    },
  },
  mounted() {
    this.content = this.detailContent;
  },
};
</script>

<style lang="less" scoped></style>
